import { nextTick } from 'vue'
import { getAppPages, getSubPackagesPages } from "@/utils/pages"

// #ifdef APP-PLUS
import pagesAuthLogin from '@/app/locale/zh-Hans/pages.auth.login.json'
import pagesAuthResetpwd from '@/app/locale/zh-Hans/pages.auth.resetpwd.json'
import pagesAuthIndex from '@/app/locale/zh-Hans/pages.auth.index.json'

import PagesSettingIndex from '@/app/locale/zh-Hans/pages.setting.index.json'
import ShopPagesShopOrder from '@/addon/shop/locale/zh-Hans/pages.shopOrder.detail.json'
const app = {
    'pages.auth.login': pagesAuthLogin,
    'pages.auth.index': pagesAuthIndex,
    'pages.auth.resetpwd': pagesAuthResetpwd,
    'pages.setting.index': PagesSettingIndex
}
const addone = {
    'pages.shopOrder.detail': ShopPagesShopOrder
}

// #endif

class Language {
    private i18n: any
    private loadLocale: Array<string> = [] //已加载的语言

    public path = ''

    constructor(i18n: any) {
        this.i18n = i18n
    }

    /**
     *
     * @param locale 设置语言
     */
    public setI18nLanguage(locale: string, path: string = '') {
        if (this.i18n.global.locale == locale) return
        this.i18n.global.locale = locale
        path && (this.path = path)
        uni.setLocale(locale)
    }

    public loadAllLocaleMessages(app: string, locale: string) {
        const pages = app == 'app' ? getAppPages() : getSubPackagesPages()
        pages.forEach((path: string) => {
            this.loadLocaleMessages(path, locale)
        })
    }

    /**
     * 加载语言包
     * @param path
     * @param locale
     * @returns
     */
    public async loadLocaleMessages(path: string, locale: string) {
        try {
            const { route, file, fileKey } = this.getFileKey(path)

            // 是否已加载
            if (this.loadLocale.includes(`${fileKey}.${locale}`)) {
                this.setI18nLanguage(locale, file)
                return nextTick()
            }
            this.loadLocale.push(`${fileKey}.${locale}`)
            // #ifndef APP-PLUS

            // 引入语言包文件
            const messages = await import(route == 'app' ? `../${route}/locale/${locale}/${file}.json` : `../addon/${route}/locale/${locale}/${file}.json`)
            // #endif

            // #ifdef APP-PLUS
            const messages = route == 'app' ? app[file] : addone[file]



            // #endif

            let data: Record<string, string> = {}
            // #ifndef APP-PLUS

            Object.keys(messages.default).forEach(key => {
                data[`${fileKey}.${key}`] = messages.default[key]
            })
            // #endif
            // #ifdef APP-PLUS

            Object.keys(messages).forEach(key => {
                data[`${fileKey}.${key}`] = messages[key]
            })
            // #endif



            this.i18n.global.mergeLocaleMessage(locale, data)
            this.setI18nLanguage(locale, file)

            return nextTick()
        } catch (e) {
            // console.log(e)
            this.setI18nLanguage(locale)
            return nextTick()
        }
    }

    public getFileKey = (path: string) => {
        const pathArr = path.split('/')
        let route = pathArr[1] == 'app' ? pathArr[1] : pathArr[2];

        // #ifndef APP-PLUS
        let file = path == '/' ? 'pages.index.index' : path.replace('/', '').replaceAll('/', '.')
        // #endif
        // #ifdef APP-PLUS
        let file = path == '/' ? 'pages.index.index' : path.replace('/', '').replace(/\//g, '.')

        // #endif

        // 如果是系统页面，则移除“app.”
        let fileKey = ''
        if (route == 'app') {
            fileKey = file.replace('app.', '')
            file = file.replace('app.', '')
        } else {
            fileKey = file.replace(`addon.`, '')
            file = file.replace(`addon.${route}.`, '')
        }
        return { file, fileKey, route }
    }
}

export default Language
